package com.yobol.jgrowth.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

/**
 * Choose CKFinder Folder
 *
 * @author
 * @create 2018-04-02 22:14
 **/

public class CKFinder {

    public String chooseUserFolder(String configPath,String imageType,String username) {
        String baseDir = "D:\\Projects\\_Resource\\JGrowth\\User\\image";
        String baseURL = "http://localhost:8080/public/image";
        File configXml = new File(configPath);
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(configXml);
            Element root = document.getRootElement();
            for (Iterator<?> i = root.elementIterator(); i.hasNext(); ) {
                Element element = (Element) i.next();
                if (element.getName().equals("baseDir")) {
                    baseDir += "\\" + imageType + "\\" + username;
                    System.out.println(baseDir);
                    element.setText(baseDir);
                }
                if (element.getName().equals("baseURL")) {
                    baseURL += "/" +  imageType + "/" + username + "/";
                    System.out.println(baseURL);
                    element.setText(baseURL);
                }
            }

            XMLWriter writer = new XMLWriter(new FileWriter(configXml));
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baseURL;
    }
}
